package com.redis.lock;

import redis.clients.jedis.Jedis;

import java.util.Collections;
import java.util.List;

public abstract class AbstractRedisLock {
    static final String LOCK_KEY = "LOCK_KEY:LOCK-HOLDER:";
    static final long DEFAULT_TIMEOUT = 20L;
    static final long RETRY_INTERVAL = 100L;

    final String lockName;

    Jedis jedis;

    long timeout;

    String unlockLua = "if redis.call('get', KEYS[1]) == ARGV[1] then" +
            " return redis.call('del', KEYS[1])" +
            " else" +
            " return 0" +
            " end";

    List<String> unlockLuaKey;

    public AbstractRedisLock(Jedis jedis, String lockName, long timeout) {
        this.jedis = jedis;
        this.lockName = LOCK_KEY + lockName;
        this.unlockLuaKey = Collections.singletonList(this.lockName);
        this.timeout = timeout;
    }

    abstract public boolean tryLock(long waitTimeOut);

    abstract public void unlock() throws RedisLockException;

    public void close() {
        if (jedis != null) {
            jedis.close();
        }
    }
}
